package com.sgb.contract.base;

import com.sgb.contract.base.viewmodel.BaseViewModel;

import java.util.Map;

import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

/**
 * 带fragment处理的BaseActivity基类扩展
 * @author cyj
 * @param <DB>
 * @param <VM>
 */
public abstract class BaseFragmentActivity<DB extends ViewDataBinding, VM extends BaseViewModel> extends BaseActivity<DB, VM> {

    /** 当前Fragment tag */
    protected String currentTag = "";
    /** Fragment[]是否加载完成 */
    private boolean isLoadDone;
    /** 默认加载第一个 */
    private boolean firstLoad;

    /**
     * 装载Activity要执行的Fragment碎片
     * @return
     */
    protected abstract Map<String, Fragment> getFragments();

    /**
     * Fragment[]是否加载完成
     * @return    isLoadDone
     */
    protected boolean isLoadDone() {
        return isLoadDone;
    }

    /**
     * 显示 Fragment
     * @param tag
     */
    public void showFragment(String tag) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

        // 隐藏上一个Fragment  fixme: 如果fragment加入太多，那么此处使用replace最优，因为过多的fragment在内存会导致性能低下
        Fragment lastFragment = getSupportFragmentManager().findFragmentByTag(currentTag);
        if(lastFragment != null) {
            fragmentTransaction.hide(lastFragment);
        }

        // 查找fragment并显示
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);

        // 加载fragment到容器
        if(!isLoadDone) {
            for (Map.Entry<String, Fragment> entry : getFragments().entrySet()) {
                if(!firstLoad && null == fragment) {
                    fragment = entry.getValue();
                }
                entry.getValue().setArguments(getIntent().getExtras());
            //    fragmentTransaction.add(R.id.fl_fragments, entry.getValue(), entry.getKey());
                fragmentTransaction.hide(entry.getValue());
            }
            firstLoad = true;
            isLoadDone = true;
        }

        if(null != fragment) {
            currentTag = fragment.getTag();
            fragmentTransaction.show(fragment);
        }
        fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        fragmentTransaction.commitNowAllowingStateLoss();
    }
}
